<template>
  <FormView
    v-model="entity"
    :title="entity.id ? '项目阶段变更单' : '新建项目阶段变更单'"
    :toolbar-attrs="{
      buttons: [
        'back',
        {
          save: isDraft || flowContext.isStartNode,
          submit: hasBtn('submit'),
          withdraw: flowContext.canWithdraw,
          reject: flowContext.canReject,
          finish: hasBtn('finish')
        }
      ]
    }"
    :toolbar-listeners="{
      save: () => saveAndStart({ title: `${userName}的项目阶段变更申请` }),
      submit: submitAudit,
      finish: () => submitAudit({}),
      withdraw: () => withdrawAudit(),
      reject: () => reject()
    }">
    <template #toolbar-right> </template>
    <FormHolder ref="form" label-width="130px" :disabled="isDisabled" :model="entity">
      <FormItemGroup block-title="基本信息">
        <FormInput :value="entity.createBy" prop="createBy" label="作者" disabled />
        <FormInput :value="entity.deptFullName" prop="deptFullName" label="所属单位" disabled />
        <FormInput :value="entity.projectName" prop="projectName" label="所属项目" disabled>
          <ElLink underline type="primary" @click="$router.push(`/tech-project/project-manage/information/ProjectInformationForm/${entity.projectId}`)">
            {{ entity.projectName }}
          </ElLink>
        </FormInput>
        <FormDatePicker v-model="entity.modifyTime" prop="modifyTime" label="变更时间" :placeholder="null" date-time disabled />
        <FormInput v-model="entity.subject" prop="subject" label="标题" required />
        <FormTextarea v-model="entity.reason" prop="reason" label="变更理由" />
      </FormItemGroup>
      <FormItemGroup enabled :gutter="0" block-title="调整列表">
        <FormTablePlus
          :key="entity.status"
          v-model="entity.stages"
          required
          label="项目阶段"
          hide-label
          prefix-pick
          :disabled="isDisabled"
          label-width="0"
          prop="stages"
          :columns="stageColumns"
          @add-row="isStageEditDialogVisible = true">
          <template #action="{ row }">
            <span :style="{ color: row.action === 2 ? 'red' : row.action === 3 ? 'orange' : 'green' }">
              {{ options[row.action] }}
            </span>
          </template>
          <template #toolbar-left="{ addRow }">
            <ElButton size="mini" class="table-header-button add" icon="el-icon-circle-plus" type="text" @click="addRow">添加</ElButton>
            <ElButton size="mini" class="table-header-button add" icon="el-icon-edit-outline" type="text" @click="adjustStage">调整</ElButton>
            <ElButton size="mini" class="table-header-button remove" icon="el-icon-remove" type="text" @click="deleteStage">删除</ElButton>
          </template>
          <template #handle="{ remove }">
            <TableColumn #default="{ row, $index }" label="操作" align="center">
              <ElButton v-if="isDraft && isCreator" size="mini" type="text" @click="addStage($index)">添加</ElButton>
              <ElButton v-if="isDraft && isCreator && row.action !== 2" size="mini" type="text" @click="editStage(row, $index)">编辑</ElButton>
              <Confirmable v-if="isDraft && isCreator" tag="ElButton" title="删除" message="您确定要删除该行吗？" size="mini" type="text" @click="remove">
                删除
              </Confirmable>
              <ElButton v-if="!isDraft" size="mini" type="text" @click="viewStage(row, $index)">查看</ElButton>
            </TableColumn>
          </template>
        </FormTablePlus>
      </FormItemGroup>
    </FormHolder>
    <StageEditDialog
      v-if="isStageEditDialogVisible"
      :value="stage"
      :disabled="isView"
      :visible.sync="isStageEditDialogVisible"
      @close="stage = null"
      @confirm="onStageConfirm" />
    <ProjectStagesDialog
      v-if="isProjectStagesDialogVisible"
      :title="dialogTitle"
      :project-id="projectId || entity.projectId"
      :disabled-row-keys="entity.stages.map(value => value.originalId).filter(value => value)"
      :multiple="multiple"
      :visible.sync="isProjectStagesDialogVisible"
      @confirm="onSelectRow" />
  </FormView>
</template>

<script>
  import { create, load, save, update } from './api'
  import flowForm from '@/vue/mixin/flow-form'
  import { stageColumns } from '@/module/tech-project/project-manage'
  import StageEditDialog from '@/module/tech-project/project-manage/stage/StageEditDialog.vue'
  import ProjectStagesDialog from '@/module/tech-project/project-manage/stage/ProjectStagesDialog.vue'

  export default {
    name: 'ProjectStageUpdateForm',
    components: { ProjectStagesDialog, StageEditDialog },
    docType: 'WF_PROJECT_STAGE',
    relativeViewId: 'ProjectStageUpdateView',
    mixins: [flowForm],
    props: {
      projectId: String
    },
    data() {
      return {
        isView: false,
        isStageEditDialogVisible: false,
        isProjectStagesDialogVisible: false,
        options: { 2: '删除', 1: '添加', 3: '调整' },
        stageColumns: [
          ...stageColumns,
          {
            label: '动作',
            prop: 'action',
            align: 'center'
          }
        ],
        dialogTitle: '',
        multiple: false,
        editIndex: null,
        stage: null,
        entity: {
          id: null,
          unid: null,
          createTime: null,
          createBy: null,
          createId: null,
          deptId: null,
          deptFullName: null,
          updateTime: null,
          updateId: null,
          updateBy: null,
          tenantId: null,
          delFlag: null,
          modifyTime: null,
          subject: null,
          reason: null,
          projectId: null,
          projectName: null,
          status: null,
          stages: []
        }
      }
    },
    methods: {
      create() {
        return create({ projectId: this.projectId })
      },
      load,
      save,
      update,
      async initEntity(id) {
        const entity = await this.loadEntity(id)
        entity.stages = entity.stages || []
        this.entity = entity
      },
      deleteStage() {
        this.multiple = true
        this.dialogTitle = '请选择要删除的阶段'
        this.isProjectStagesDialogVisible = true
      },
      adjustStage() {
        this.multiple = false
        this.dialogTitle = '请选择要调整的阶段'
        this.isProjectStagesDialogVisible = true
      },
      onSelectRow(rows) {
        if (this.multiple) {
          // 删除
          this.entity.stages.push(
            ...rows.map(value => {
              value.action = 2
              value.rootId = value.rootId || value.id
              value.originalId = value.id
              value.id = null
              return value
            })
          )
        } else {
          // 调整
          rows.action = 3
          rows.rootId = rows.rootId || rows.id
          rows.originalId = rows.id
          rows.id = null
          this.stage = rows
          this.isStageEditDialogVisible = true
        }
      },
      addStage(index) {
        this.editIndex = index
        this.isStageEditDialogVisible = true
      },
      viewStage(row) {
        this.stage = row
        this.isView = true
        this.isStageEditDialogVisible = true
      },
      editStage(row, index) {
        this.editIndex = index
        this.stage = row
        this.isStageEditDialogVisible = true
      },
      onStageConfirm(stage) {
        if (this.editIndex !== null && this.stage) {
          // 编辑
          this.$set(this.entity.stages, this.editIndex, stage)
          this.editIndex = null
          this.stage = null
        } else if (this.editIndex !== null) {
          // 操作添加
          stage.action = stage.action || 1
          this.entity.stages.splice(this.editIndex + 1, 0, stage)
        } else {
          // 顶部添加
          stage.action = stage.action || 1
          this.entity.stages.push(stage)
        }
      }
    }
  }
</script>
